package com.zxl.live.screen.call.helper;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;

/**
 * Created by Administrator on 2017/12/11.
 */

public class ContactHelper {

    public static ContactUser fetchContactIdFromPhoneNumber(Context context, String phoneNumber) {
        Cursor cursor = null;
        try {
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
            cursor = context.getContentResolver().query(uri,
                    new String[]{ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.PHOTO_URI},
                    null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    String id = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
                    String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
                    String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_URI));
                    if (!TextUtils.isEmpty(photoUri)) {
                        //https://github.com/nostra13/Android-Universal-Image-Loader/issues/836
                        photoUri = "content://com.android.contacts/contacts/" + id;
                    }
                    return new ContactUser(contactName, photoUri);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            //column 'data1' does not existjava.lang.RuntimeException
            e.printStackTrace();
            return null;
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
        return null;
    }

    public static class ContactUser {
        String mUserName;
        String mPhotoUri;

        public ContactUser(String userName, String photoUri) {
            mUserName = userName;
            mPhotoUri = photoUri;
        }

        public String getUserName() {
            return mUserName;
        }

        public String getPhotoUri() {
            return mPhotoUri;
        }

        @Override
        public String toString() {
            return "ContactUser{" +
                    "mUserName='" + mUserName + '\'' +
                    ", mPhotoUri='" + mPhotoUri + '\'' +
                    '}';
        }
    }

}
